/*
 * @lc app=leetcode.cn id=98 lang=typescript
 *
 * [98] 验证二叉搜索树
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

function isValidBST(root: TreeNode | null): boolean {
  let pre: TreeNode | null = null;
  const inorder = (root: TreeNode | null): boolean => {
    if (root === null) return true;
    // 左树无效
    if (!inorder(root.left)) return false;
    // 非递增，表示不是有效二叉搜索树
    if (pre && pre.val >= root.val) return false;
    // 记录前一个结点
    pre = root;
    // 右树无效
    if (!inorder(root.right)) return false;
    return true;
  };
  return inorder(root);
}
// @lc code=end
